package com.cheng.xbjy.service.impl;

import com.cheng.xbjy.dao.ArticleDao;
import com.cheng.xbjy.entity.Article;
import com.cheng.xbjy.entity.User;
import com.cheng.xbjy.entity.vo.PageResult;
import com.cheng.xbjy.entity.vo.Result;
import com.cheng.xbjy.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleDao articleDao;

    @Override
    public Page<Article> findPage(String title, Integer page) {
        if (StringUtils.isEmpty(title)) {
            return articleDao.findAll(PageRequest.of(page - 1, PageResult.PAGE_SIZE));
        }
        return articleDao.findByTitleLike("%" + title + "%", PageRequest.of(page - 1, PageResult.PAGE_SIZE));
    }

    @Override
    public void save(Article article, User loginUser) {
        article.setBrowseCount(0L);
        article.setPublishDate(new Date());
        article.setPublishRealName(loginUser.getRealName());
        article.setUserId(loginUser.getId());
        articleDao.save(article);
    }

    @Transactional
    @Override
    public Map<String, Object> findDetail(Long articleId, Long userId) {
        Map<String, Object> map = new HashMap<>();
        Article article = articleDao.findById(articleId).get();
        //查询收藏次数
        Integer favorites = articleDao.countByArticleId(articleId);

        //更新查看次数
        articleDao.updateLook(articleId);

        //当前登录用户是否关注该文章
        Integer isFollow = articleDao.findByArticleIdAndUserId(articleId, userId);

        //查看当前用户关注的人也收藏了该文章的用户
        List<User> userList = articleDao.findUserFollow(articleId, userId);

        map.put("article", article);
        map.put("favorites", favorites);
        map.put("isFollow", isFollow);
        map.put("userList", userList);
        return map;
    }

    @Transactional
    @Override
    public Result doFavorite(Long articleId, Long userId) {
        Integer isFollow = articleDao.findByArticleIdAndUserId(articleId, userId);
        if (isFollow > 0) {
            articleDao.deleteByArticleIdAndUserId(articleId, userId);
            return new Result(false, "取消收藏成功", articleDao.countByArticleId(articleId));
        }
        articleDao.saveByArticleIdAndUserId(userId, articleId);
        return new Result(true, "收藏成功", articleDao.countByArticleId(articleId));
    }

    @Override
    public Page<Article> findFavoritePage(String title, Integer page, Long userId) {
        return articleDao.findFavoritePage("%" + title + "%", userId, PageRequest.of(page - 1, PageResult.PAGE_SIZE));
    }

}
